package com.ityuwen.mengyagushi.dispatch.job;

import com.ityuwen.mengyagushi.common.result.Result;
import com.ityuwen.mengyagushi.dispatch.mapper.XxlJobLogMapper;
import com.ityuwen.mengyagushi.model.dispatch.XxlJobLog;
import com.ityuwen.mengyagushi.search.client.SearchFeignClient;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SearchJobHandler {

    @Autowired
    private SearchFeignClient searchFeignClient;

    @Autowired
    private XxlJobLogMapper xxlJobLogMapper;

    @XxlJob("searchSyncAlbuStatToEs")
    public void syncAlbumStatToEs(){
        long startTime = System.currentTimeMillis(); // 起始时间
        XxlJobLog xxlJobLog = new XxlJobLog();
        try {

            Result result = this.searchFeignClient.updateRanking();
            if (result != null) {
                xxlJobLog.setStatus(1);
            } else {
                xxlJobLog.setStatus(0);
                xxlJobLog.setError("远程调用search服务的接口失败！");
            }
        } catch (Exception ex){
            ex.printStackTrace();
            xxlJobLog.setStatus(0);
            xxlJobLog.setError(ex.getMessage());
        } finally {
            // 计算任务的执行时间
            long endTime = System.currentTimeMillis();
            long times = endTime - startTime;
            xxlJobLog.setJobId(XxlJobHelper.getJobId());
            xxlJobLog.setTimes((int)times);
            this.xxlJobLogMapper.insert(xxlJobLog);
        }
    }
}
